﻿using System.Collections.Generic;
using UnityEngine;

namespace winS.Unity
{
    /// <summary>
    /// 表示协程所有者
    /// </summary>
    internal class CoroutineOwner : MonoBehaviour
    {
        private bool destroying;

        private List<Coroutine> coroutineList;

        public void AddCoroutine(Coroutine coroutine)
        {
            if (coroutineList.Contains(coroutine)) return;
            coroutineList.Add(coroutine);
            coroutine.onFinished += () =>
            {
                if (destroying) return;
                coroutineList.Remove(coroutine);
            };
        }

        private void Awake()
        {
            coroutineList = new List<Coroutine>();
        }
        private void OnDestroy()
        {
            destroying = true;
            if (coroutineList == null) return;//防止编辑器下编译后脚本报空
            foreach (var coroutine in coroutineList) coroutine.Stop();
        }
    }
}